package com.noble.library.time;

import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.format.Time;

import com.noble.library.basic.convert.TypeConvertUtil;
import com.noble.library.basic.log.PLogger;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.Period;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 时间处理类
 */
public class TimeUtil {
    // ============================ Joda Time 处理  =============================

    /**
     * RFC3339时间格式对应时间戳
     *
     * @param rfcDateString RFC3339格式时间串
     */
    public static long rfcDateTime(String rfcDateString) {
        DateTime dateTime = new DateTime(rfcDateString);
        return dateTime.toCalendar(Locale.getDefault()).getTimeInMillis();
    }

    /**
     * 两个时间相差天数(不可用： 计算不准)
     *
     * @param oldTime 相比较的前时间（毫秒）
     */
    public static int getIntervalDay(long oldTime, long currentTime) {
        Interval interval = new Interval(oldTime, currentTime);
        Period p = interval.toPeriod();
        return p.getDays();
    }

    /**
     * 相差天数
     */
    public static long getIntervalDays(long oldTime, long current) {
        return (current - oldTime) / (24 * 60 * 60 * 1000);
    }

    /**
     * RFC3339是否是默认空值
     */
    public static boolean rfcNull(String rfcDateString) {
        return TextUtils.equals(rfcDateString, "0001-01-01T00:00:00Z");
    }

    // ============================ 原生处理方法 =============================

    /**
     * 转化毫秒时间戳为对应格式
     */
    public static String formatTime(long time, String toFormal) {
        String ret = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(toFormal, Locale.getDefault());
            ret = sdf.format(new Date(time));
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
        return ret;
    }

    /**
     * RFC3339转化为 toFormal 格式的字符串
     *
     * @param formalTime RFC3339格式时间串
     */
    public static String rfcFormalTime(String formalTime, String toFormal) {
        SimpleDateFormat sdf = new SimpleDateFormat(FormatPattern.FP_RFC3339, Locale.getDefault());
        Date d;
        try {
            d = sdf.parse(formalTime);
            SimpleDateFormat nsdf = new SimpleDateFormat(toFormal, Locale.getDefault());
            return nsdf.format(d);
        } catch (ParseException e) {
            return "";
        }
    }

    /**
     * 传入年月日，返回"yyyy-MM-dd"
     */
    public static String simpleFormatStr(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        Date d = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(FormatPattern.FP_YMD, Locale.getDefault());
        String strTime = "";
        strTime = sdf.format(d);
        return strTime;
    }

    /**
     * 获取当前年份
     */
    public static int getCurrentYear() {
        Time time = new Time();
        time.setToNow();
        return time.year;
    }

    /**
     * 获取当前本地时间秒
     */
    public static long getCurrentTimeMil() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获取当前年月日往后推几天的时间  2016年01月26日
     *
     * @param dayAddNum 推后时间
     */
    public static String getRetardDateStr(int dayAddNum, long current) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        if (current <= 0) {
            current = System.currentTimeMillis();
        }
        long tmp = (dayAddNum * 24 * 60 * 60 * 1000) + current;
        Date curDate = new Date(tmp);// 获取当前日期往后推几天的日期
        return formatter.format(curDate);
    }

    /**
     * 补齐 毫秒
     */
    public static long onPad(long number) {
        try {
            int poslength = 13;
            int length = String.valueOf(number).length();
            int remaining = poslength - length;
            if (remaining > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append(number);
                for (int i = 0; i < remaining; i++) {
                    sb.append(0);
                }
                return TypeConvertUtil.toLong(sb.toString(), System.currentTimeMillis());
            } else {
                return TypeConvertUtil.toLong(String.valueOf(number).substring(0, 13), System.currentTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return System.currentTimeMillis();
        }
    }

    /**
     * 月日时分秒，0-9前补0
     */
    @NonNull
    public static String fillZero(int number) {
        return number < 10 ? "0" + number : "" + number;
    }
}
